package com.boomsecret.classloader;

import java.io.*;
import java.util.Objects;

/**
 * Created by wangjinliang on 2018/1/31.
 */
public class CustomAClassLoader extends ClassLoader {
    private String filePath = null;

    protected synchronized Class<?> findClassByFilePathAndName(String filePath, String name)
            throws ClassNotFoundException {
        if (Objects.isNull(filePath) || Objects.isNull(name)) {
            throw new IllegalArgumentException("参数不能为空");
        }
        this.filePath = filePath;
        return findClass(name);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(filePath)
                .append(name.replace(".", "/"))
                .append(".class");

        FileInputStream fis = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            fis = new FileInputStream(new File(stringBuilder.toString()));
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = fis.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }
            return this.defineClass(name, baos.toByteArray(), 0, baos.size());
        } catch (Exception e) {
            throw new ClassNotFoundException();
        } finally {
            closeStream(fis);
            closeStream(baos);
        }
    }

    private void closeStream(InputStream stream) {
        if (Objects.nonNull(stream)) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void closeStream(OutputStream stream) {
        if (Objects.nonNull(stream)) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
